#-*- coding: utf-8 -*-
'''
Created on 2.14, 2016
@author: XFBY
'''
import requests as req
import re 
import json
pass
class trainTicketsSprider:
    def getTicketsInfo(self,purpose_codes,query_data,from_station,to_station):
        self.url = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=%s&queryDate=%s&from_station=%s&to_station=%s'%(purpose_codes,query_data,from_station,to_station)
        self.headers = {
                    "Accept":"text/html,application/xhtml+xml,application/xml;",
                    "Accept-Encoding":"gzip",
                    "Accept-Language":"zh-CN,zh;q=0.8",
                    "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
                  }
        self.ts = req.Session()
        self.ts.verify = False
        self.ts.headers = self.headers
        self.content = self.ts.get(self.url)
        self.result = json.loads(self.content.text)["data"]["datas"]
        return self.result
def isZero(num):
    if num == r'--' or r'无':
        return '0'
    else :
        return num
    pass
def main():
    purpose = 'ADULT'
    query_d = '2016-03-28'
    from_stat = 'NCG'
    to_sta = 'CZQ'
    tickS = trainTicketsSprider()
    res = tickS.getTicketsInfo(purpose,query_d,from_stat,to_sta)
    for i,ticketInfo in enumerate(res):
        print(i)
        print(u"车次：%s" %ticketInfo["station_train_code"])
        print(u"起始站:%s" %ticketInfo["start_station_name"])
        print(u"目的地:%s" %ticketInfo["to_station_name"])
        print(u"开车时间:%s" %ticketInfo["start_time"])
        print(u"到达时间:%s"%ticketInfo["arrive_time"])
        print(u"二等座还剩:%s张票" %isZero(ticketInfo["ze_num"]))
        print(u"硬座还剩:%s张票" %isZero(ticketInfo["yz_num"]))
        print(u"硬卧还剩:%s张票" %isZero(ticketInfo["yw_num"]))
        print(u"无座还剩:%s张票"%isZero(ticketInfo["wz_num"]))
        print(u"tickets:%s" %ticketInfo["canWebBuy"])
        print("**********************************")
    pass
if __name__ == '__main__':
    main()
